package miao.byusi.android.properos;

import android.annotation.SuppressLint;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.webkit.JavascriptInterface;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Toast;

import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity {

    private WebView webView;
    private static final String TAG = "ProperOS";

    @SuppressLint("SetJavaScriptEnabled")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        
        setupImmersiveMode();
        
        webView = findViewById(R.id.webview);
        setupWebView();
        
        // 初始化应用目录
        initAppDirectory();
        
        webView.loadUrl("file:///android_asset/properos/framework/properos.html");
    }

    private void setupImmersiveMode() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
            WindowManager.LayoutParams params = getWindow().getAttributes();
            params.layoutInDisplayCutoutMode = WindowManager.LayoutParams.LAYOUT_IN_DISPLAY_CUTOUT_MODE_SHORT_EDGES;
            getWindow().setAttributes(params);
        }
        
        View decorView = getWindow().getDecorView();
        int uiOptions = View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
                      | View.SYSTEM_UI_FLAG_FULLSCREEN
                      | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY;
        decorView.setSystemUiVisibility(uiOptions);
    }

    private void setupWebView() {
        WebSettings webSettings = webView.getSettings();
        webSettings.setJavaScriptEnabled(true);
        webSettings.setDomStorageEnabled(true);
        webSettings.setDatabaseEnabled(true);
        webSettings.setCacheMode(WebSettings.LOAD_DEFAULT);
        
        webView.setWebViewClient(new WebViewClient());
        webView.setWebChromeClient(new WebChromeClient());
        
        webView.addJavascriptInterface(new ProperOSInterface(this), "ProperOSAndroid");
    }

    private void initAppDirectory() {
        File appDir = new File(getExternalFilesDir(null), "properos/apps");
        if (!appDir.exists()) {
            appDir.mkdirs();
        }
    }

    public class ProperOSInterface {
        private final MainActivity activity;

        public ProperOSInterface(MainActivity activity) {
            this.activity = activity;
        }

        @JavascriptInterface
        public void showToast(String message) {
            activity.runOnUiThread(() -> 
                Toast.makeText(activity, message, Toast.LENGTH_SHORT).show());
        }

        @JavascriptInterface
        public String getSystemInfo() {
            return Build.MANUFACTURER + " " + Build.MODEL + " | Android " + Build.VERSION.RELEASE;
        }

        @JavascriptInterface
        public String getInstalledApps() {
            List<AppInfo> apps = getInstalledAppList();
            JSONArray jsonArray = new JSONArray();
            
            for (AppInfo app : apps) {
                JSONObject jsonObject = new JSONObject();
                try {
                    jsonObject.put("id", app.packageName);
                    jsonObject.put("name", app.name);
                    jsonObject.put("version", app.versionName);
                    jsonObject.put("icon", app.iconPath);
                    jsonArray.put(jsonObject);
                } catch (JSONException e) {
                    Log.e(TAG, "Error creating JSON", e);
                }
            }
            
            return jsonArray.toString();
        }

        @JavascriptInterface
        public boolean installApp(String appData) {
            try {
                JSONObject appJson = new JSONObject(appData);
                String appId = appJson.getString("id");
                String appName = appJson.getString("name");
                
                // 保存应用到本地存储
                File appDir = new File(getExternalFilesDir(null), "properos/apps");
                File appFile = new File(appDir, appId + ".json");
                
                try (FileOutputStream fos = new FileOutputStream(appFile)) {
                    fos.write(appData.getBytes());
                }
                
                return true;
            } catch (Exception e) {
                Log.e(TAG, "Error installing app", e);
                return false;
            }
        }

        @JavascriptInterface
        public boolean uninstallApp(String appId) {
            File appFile = new File(getExternalFilesDir(null), "properos/apps/" + appId + ".json");
            return appFile.delete();
        }

        @JavascriptInterface
        public String getAppInfo(String appId) {
            File appFile = new File(getExternalFilesDir(null), "properos/apps/" + appId + ".json");
            if (appFile.exists()) {
                try {
                    InputStream is = new java.io.FileInputStream(appFile);
                    byte[] buffer = new byte[(int) appFile.length()];
                    is.read(buffer);
                    is.close();
                    return new String(buffer);
                } catch (IOException e) {
                    Log.e(TAG, "Error reading app file", e);
                }
            }
            return null;
        }

        private List<AppInfo> getInstalledAppList() {
            List<AppInfo> apps = new ArrayList<>();
            PackageManager pm = activity.getPackageManager();
            
            // 获取ProperOS应用
            File appDir = new File(getExternalFilesDir(null), "properos/apps");
            if (appDir.exists() && appDir.isDirectory()) {
                File[] files = appDir.listFiles((dir, name) -> name.endsWith(".json"));
                if (files != null) {
                    for (File file : files) {
                        try {
                            InputStream is = new java.io.FileInputStream(file);
                            byte[] buffer = new byte[(int) file.length()];
                            is.read(buffer);
                            is.close();
                            
                            JSONObject appJson = new JSONObject(new String(buffer));
                            AppInfo appInfo = new AppInfo();
                            appInfo.packageName = appJson.getString("id");
                            appInfo.name = appJson.getString("name");
                            appInfo.versionName = appJson.optString("version", "1.0");
                            appInfo.iconPath = appJson.optString("icon", "");
                            apps.add(appInfo);
                        } catch (Exception e) {
                            Log.e(TAG, "Error reading app file", e);
                        }
                    }
                }
            }
            
            // 获取系统应用 (可选)
            List<PackageInfo> packages = pm.getInstalledPackages(0);
            for (PackageInfo packageInfo : packages) {
                if ((packageInfo.applicationInfo.flags & android.content.pm.ApplicationInfo.FLAG_SYSTEM) == 0) {
                    AppInfo appInfo = new AppInfo();
                    appInfo.packageName = packageInfo.packageName;
                    appInfo.name = packageInfo.applicationInfo.loadLabel(pm).toString();
                    appInfo.versionName = packageInfo.versionName;
                    apps.add(appInfo);
                }
            }
            
            return apps;
        }
    }

    private static class AppInfo {
        String packageName;
        String name;
        String versionName;
        String iconPath;
    }

    @Override
    protected void onResume() {
        super.onResume();
        setupImmersiveMode();
    }

    @Override
    public void onBackPressed() {
        if (webView.canGoBack()) {
            webView.goBack();
        } else {
            new AlertDialog.Builder(this)
                .setTitle("退出提示")
                .setMessage("确定要退出ProperOS吗？")
                .setPositiveButton("退出", (dialog, which) -> finish())
                .setNegativeButton("取消", null)
                .show();
        }
    }

    @Override
    protected void onDestroy() {
        if (webView != null) {
            webView.destroy();
        }
        super.onDestroy();
    }
}